package com.jetinno.simple;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jetinno.utils.InputMethodUtil;
import com.jetinno.utils.LoadMvpView;
import com.jetinno.utils.LogUtils;
import com.jetinno.utils.SimpleCallback;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by zhangyuncai on 2021/7/14.
 */
public abstract class SimpleFragment extends Fragment implements View.OnClickListener, LoadMvpView {
    protected String TAG = this.getClass().getSimpleName();
    protected Context mContext;
    public FragmentActivity mActivity;
    protected View rootView;
    protected boolean isViewPrepared; // 标识fragment视图已经初始化完毕
    protected boolean hasFetchData; // 标识已经触发过懒加载数据
    protected CompositeDisposable mCompositeDisposable = new CompositeDisposable();
    protected final List<SimplePresenter> presenters = new ArrayList<>();
    ;
    protected boolean isRegisterEventBus = false;

    protected void addPresenter(SimplePresenter presenter) {
        presenters.add(presenter);
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        logLify("onCreateView");
        if (rootView == null) {
            rootView = inflater.inflate(getLayoutId(), container, false);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    protected abstract int getLayoutId();

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        findViewByIds();
        if (isRegisterEventBus) {
            EventBus.getDefault().register(this);
        }
        initView();
        initEvent();
        if (rootView != null) {
            rootView.setOnClickListener(v -> {//防止事件击穿

            });
        }
    }

    protected  void findViewByIds(){}
    protected <T extends View> T findViewById(@IdRes int id) {
        return rootView.findViewById(id);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewPrepared = true;
        lazyFetchDataIfPrepared();
    }

    protected void runOnUiThread(Runnable runnable) {
        getActivity().runOnUiThread(runnable);
    }

    ///开启定时器
    protected void delay(long delay, SimpleCallback<Object> callback) {
        Disposable subscribe = Observable.timer(delay, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    callback.callback(true);
                }, throwable -> {
                    LogUtils.logException(TAG,throwable);
                });
        mCompositeDisposable.add(subscribe);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mCompositeDisposable != null && !mCompositeDisposable.isDisposed()) {
            mCompositeDisposable.dispose();
        }
        hasFetchData = false;
        isViewPrepared = false;
        if (isRegisterEventBus) {
            EventBus.getDefault().unregister(this);
        }
        InputMethodUtil.closeKeyBoard(mActivity);
        for (SimplePresenter presenter : presenters) {
            presenter.onDestory();
        }
        logLify("onDestroyView");
    }


    //懒加载相关*********************************************************************************************************
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        logLify("setUserVisibleHint:" + isVisibleToUser);
        if (isVisibleToUser) {
            lazyFetchDataIfPrepared();
        }
    }

    protected void lazyFetchDataIfPrepared() {
        // 用户可见fragment && 没有加载过数据 && 视图已经准备完毕
        if (getUserVisibleHint() && !hasFetchData && isViewPrepared) {
            hasFetchData = true;
            lazyFetchData();
        }

    }

    /**
     * 懒加载的方式获取数据，仅在满足fragment可见和视图已经准备好的时候调用一次
     */
    protected abstract void lazyFetchData();

    @Override
    public void onAttach(Context mContext) {
        super.onAttach(mContext);
        if (mContext != null) {
            this.mContext = mContext;
        } else {
            this.mContext = getActivity();
        }
        if (this.mContext != null) {
            mActivity = (FragmentActivity) this.mContext;
        }
    }

    protected abstract void initView();

    protected abstract void initEvent();

    protected void addOnClick(int... ids) {
        for (int id : ids) {
            findViewById(id).setOnClickListener(v -> {
                onClick(v);
            });
        }
    }

    public void showLoadingBar(String msg) {
        if (mActivity != null && mActivity instanceof LoadMvpView) {
            ((LoadMvpView) mActivity).showLoadingBar(msg);
        }
    }

    public void dismissLoadingBar() {
        if (mActivity != null && mActivity instanceof LoadMvpView) {
            ((LoadMvpView) mActivity).dismissLoadingBar();
        }
    }

    public void onClick(View v) {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        logLify("onHiddenChanged:" + hidden);
    }

    protected boolean viewIsNull() {
        return rootView == null;
    }

    /**
     * 打印生命周期
     *
     * @param state
     */
    private void logLify(String state) {
        LogUtils.logOperation(TAG, state);
    }


}
